<?php

App::uses('AppModel', 'Model');
App::uses('CompositeKeyModel', 'Model');

/**
 * OrganisationMemberCategory Model
 *
 * @property OrganisationMemberCategoryType $OrganisationMemberCategoryType
 * @property OrganisationMemberGroup $OrganisationMemberGroup
 */
class OrganisationMemberCategory extends CompositeKeyModel {

    //The Associations below have been created with all possible keys, those that are not needed can be removed

    public $useDbConfig = "organisations";
    public $primaryKeys = array('id', 'organisation_id');

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'Organisation' => array(
            'className' => 'Organisation',
            'foreignKey' => 'organisation_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    /**
     * hasMany associations
     *
     * @var array
     */
    public $hasMany = array(
        'OrganisationMember' => array(
            'className' => 'OrganisationMember',
            'foreignKey' => 'organisation_member_category_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'OrganisationMemberCategorySetting' => array(
            'className' => 'OrganisationMemberCategorySetting',
            'foreignKey' => 'organisation_member_category_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    /**
     * Returns data about a specific member category for an organisation
     * 
     * @param int $organisation_id
     * @param int $category_id
     * @return array
     */
    public function getCategory($organisation_id, $category_id) {
        
        $conditions = array(
            'OrganisationMemberCategory.organisation_id' => $organisation_id
        );
        
        // filter by category if not -1
        if( $category_id != -1 ) {
            $conditions['OrganisationMemberCategory.id'] = $category_id;
        }
        
        $result = $this->find('first', array(
            'contain' => array(
                "OrganisationMember" => array(
                    'fields' => array('COUNT(id) AS member_count')
                ),
                'OrganisationMemberCategorySetting' => array(
                    'MemberCategorySetting'
                )
            ),
            'conditions' => $conditions
        ));
        
        $response = array(
            'category' => array(
                'id' => $result['OrganisationMemberCategory']['id'],
                'name' => $result['OrganisationMemberCategory']['name'],
                'description' => $result['OrganisationMemberCategory']['description'],
                'member_count' => isset($result['OrganisationMember'][0]['OrganisationMember'][0]) ? $result['OrganisationMember'][0]['OrganisationMember'][0]['member_count'] : 0
            ),
            'settings' => array()
        );
        
        foreach($result['OrganisationMemberCategorySetting'] as $setting) {
            $response['settings'][$setting['MemberCategorySetting']['name']] = $setting['value'];
        }
        
        return $response;
    }
    
    /**
     * Returns data about a specific member category for an organisation
     * 
     * @param int $organisation_id
     * @return array
     */
    public function getCategories($organisation_id) {
        $results = $this->find('all', array(
            'contain' => array(
                "OrganisationMember" => array(
                    'fields' => array('COUNT(id) AS member_count')
                ),
                'OrganisationMemberCategorySetting' => array(
                    'MemberCategorySetting'
                )
            ),
            'conditions' => array(
                'OrganisationMemberCategory.organisation_id' => $organisation_id
            ),
            'order' => array('OrganisationMemberCategory.name')
        ));
        
        
        $response = array();
        
        foreach($results as $result) {
            $category = array(
                'category' => array(
                    'id' => $result['OrganisationMemberCategory']['id'],
                    'name' => $result['OrganisationMemberCategory']['name'],
                    'description' => $result['OrganisationMemberCategory']['description'],
                    'default' => $result['OrganisationMemberCategory']['default'],
                    'member_count' => isset($result['OrganisationMember'][0]['OrganisationMember'][0]) ? $result['OrganisationMember'][0]['OrganisationMember'][0]['member_count'] : 0
                ),
                'settings' => array()
            );

            foreach($result['OrganisationMemberCategorySetting'] as $setting) {
                $category['settings'][$setting['MemberCategorySetting']['name']] = $setting['value'];
            }
            
            $response[] = $category;
        }
        
        return $response;
    }
    
    /**
     * Save membership category data
     * 
     * @param type $data
     * @return type
     */
    public function updateCategory($data) {
        
        if( $data ) {
            
            if( isset($data['OrganisationMemberCategory']['default']) && $data['OrganisationMemberCategory']['default'] == 1 ) {
                $this->updateAll(array('OrganisationMemberCategory.default' => 0), 
                        array('OrganisationMemberCategory.organisation_id' => $data['OrganisationMemberCategory']['organisation_id']));
            }
            
            $saved = $this->saveAll($data);
            
            if( $saved ) {
                $data = array(
                    'category_id' => $this->id
                );
                
                return array('status' => 'success', 'message' => 'Organisation membership category created', 'data' => $data);
            }
            
            return array('status' => 'failed', 'message' => 'Failed to create membership category');
        }
        
        return array('status' => 'failed', 'message' => 'No data supplied to save');
    }
    
    /**
     * Creates the default member category if not present
     * 
     * @param type $organisation_id
     * @return type
     */
    public function populateDefault($organisation_id) {
        
        $default = $this->getDefaultCategory($organisation_id);
        
        if( $default ) {
            return $default['OrganisationMemberCategory'];
        }
        
        // create default organisation member categories
        $settings_data = ClassRegistry::init('MemberCategorySetting')->find('all', array(
            'recursive' => -1
        ));
        
        $mc_settings = array();
        
        foreach($settings_data as $setting) {
            $mc_settings[] = array(
                'organisation_id' => $organisation_id,
                'member_category_setting_id' => $setting['MemberCategorySetting']['id'],
                'value' => $setting['MemberCategorySetting']['id']
            );
        }
        
        $categories = array(
            'OrganisationMemberCategory' => array(
                'organisation_id' => $organisation_id,
                'name' => 'Members',
                'descriptions' => 'General members of this organisation',
                'default' => 1,
                'active' => 1
            ),
            'OrganisationMemberCategorySetting' => $mc_settings
        );

        $this->saveAll($categories);
        
        $default = $this->getDefaultCategory($organisation_id);
        
        return $default['OrganisationMemberCategory'];
    }
    
    public function getDefaultCategory($organisation_id) {
        return $this->find('first', array(
            'conditions' => array(
                'OrganisationMemberCategory.default' => 1,
                'OrganisationMemberCategory.organisation_id' => $organisation_id,
                'OrganisationMemberCategory.active' => 1
            ),
            'recursive' => -1
        ));
    }
}
